package gs.android.bingomathfree;

import java.io.File;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.view.Window;
import android.widget.Button;

public class PlayDialog extends Dialog {
	private Button yes, no;
	private BingoActivity activity;

	public PlayDialog(Context context) {
		super(context);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.play);
		
		activity = (BingoActivity) context;
		
		yes = (Button) findViewById(R.id.btnPlayAgainYes);
		yes.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dismiss();
				activity.startNewGame();
			}
		});
		
		no = (Button) findViewById(R.id.btnPlayAgainNo);
		no.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SharedPreferences sp = activity.getSharedPreferences("bingo", Activity.MODE_PRIVATE);
				
				try {
					for (File f : activity.getCacheDir().getParentFile().listFiles())
						if (f.getName().equals("databases"))
							clearCache(f);
					clearCache(activity.getCacheDir());
				} catch (Exception e) {
	    			   
				}
				
				boolean rated = sp.getBoolean("rated", false);
 	   			int played = sp.getInt("played", 0);
				if (played >= 5 && !rated) {
					long t = sp.getLong("rate_time", GregorianCalendar.getInstance().getTimeInMillis());
					long now = GregorianCalendar.getInstance().getTimeInMillis();
					if (now >= t)
						activity.setResult(Activity.RESULT_OK);
					else
						activity.setResult(Activity.RESULT_CANCELED);
				} else
					activity.setResult(Activity.RESULT_CANCELED);
				
				activity.finish();
				dismiss();
			}
		});
	}

	private void clearCache(File f) {
		try {
			for (File child : f.listFiles()) {
				if (child.isDirectory()) {
					clearCache(child);
				} else {
					child.delete();
				}
			}
		} catch (Exception e) {
			
		}
	}
}